package json;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import vo.DataTableReturnObject;

import common.DropUtil;

public class DatatablesFormatter {

/**
 * 把获取的数据再度格式化进行返回
 * @param list
 * @param paramMap
 * @return
 */	
	public static DataTableReturnObject getFormatData(List list,HashMap<String, String> paramMap){
		Long count = 1L*list.size();
		String sEcho = paramMap.get("sEcho");
		return new DataTableReturnObject(count.longValue(), count.longValue(), sEcho, format(list,paramMap));
	}

/**
 * 根据查询结果和页面设定参数，组成Datatables需要的数据
 * @param list
 * @param paramMap
 * @return
 */	
	public static Object[][] format(List list,HashMap<String, String> paramMap){
		int recordCount = list.size();
		int colCount=Integer.parseInt(paramMap.get("iColumns"));
		int start = Integer.parseInt(paramMap.get("iDisplayStart"));//从0开始
		int length = Integer.parseInt(paramMap.get("iDisplayLength"));
		Object[][] objs = null;
		if(start+length>recordCount){
			objs = new Object[start+length-recordCount][];
		}else {
			objs = new Object[length][];
		}
		String[] colNames=new String[colCount];
		String[] dropNames=new String[colCount];
		
		//获取colName、dropName参数
		for(int k=0;k<colCount;k++){
			colNames[k]=paramMap.get("colName_"+k);
			dropNames[k]=paramMap.get("dropName_"+k);
		}
		//获取数据		
		for(int i=0; i<recordCount; i++) {
			if(i<start)
				continue;
			if((i-start+1)>length)
				break;	
			Map map = (Map) list.get(i);
			Object[] obj=new Object[colCount];
			for(int j=0;j<colCount;j++){
				if(StringUtils.isBlank(dropNames[j]))
					obj[j]=map.get(colNames[j]);
				else {
					obj[j]=DropUtil.getDropLabel(dropNames[j], map.get(colNames[j])==null?"":map.get(colNames[j]).toString());
				}
			}
			objs[i%length] = obj;
		}		
		
		return objs;
	}
}
